package servlet;

import com.google.gson.Gson;
import dao.impl.CommentDaoImpl;
import entity.Comment;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/comment")
public class CommentServlet extends HttpServlet {
    PrintWriter pw;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        pw = resp.getWriter();
        String operation = req.getParameter("operation");
        if(operation.equals("insert")){
            insertComment(req);
        }
        if(operation.equals("findCommentById")){
            findCommentById(req);
        }
    }

    private void findCommentById(HttpServletRequest req) {
        int newsId = Integer.parseInt(req.getParameter("newsId"));
        try {
            List<Comment> list = new CommentDaoImpl().findCommentById(newsId);
            Gson gson = new Gson();
            String commentJson = gson.toJson(list);
            System.out.println(commentJson);
            pw.write(commentJson);
            pw.flush();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    private void insertComment(HttpServletRequest req) {
        int userid = Integer.parseInt(req.getParameter("userid"));
        int articleid = Integer.parseInt(req.getParameter("articleid"));
        String userName = req.getParameter("userName");
        String commentContent = req.getParameter("comment");
        String createTiem = req.getParameter("createTime");
        try {
            userName = new String(userName.getBytes("iso8859-1"),"UTF-8");
            commentContent = new String(commentContent.getBytes("iso8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Comment comment = new Comment(articleid,userid,commentContent,userName,createTiem);
        try {
            int result = new CommentDaoImpl().insertComment(comment);
            if(result>0){
                pw.write("success");
                pw.flush();
            }else{
                pw.write("failure");
                pw.flush();
            }
            System.out.println(result+"");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
